# 创建一个请求日志，性能日志记录中间件

import time

import logging
from django.http import HttpResponse
import traceback

from sentry_sdk import capture_exception, capture_message
from . import dingtalk
logger = logging.getLogger(__name__)


# 中间件形式1:函数形式
def performance_logger_middleware(get_response):

    def middle(request):
        start_time = time.time()
        response = get_response(request)
        duration = time.time() - start_time
        response['X-Page-Duration-ms'] = int(duration * 1000)
        logger.info('%s %s %s',duration,request.path,request.GET.dict())
        return response

    return middle


# 中间件形式2:类形式
class PerformanceAndExceptionLoggerMiddleware:
    def __init__(self,get_response):
        self.get_response = get_response

    def __call__(self,request):
        start_time = time.time()
        response = self.get_response(request)
        duration = time.time() - start_time
        response['X-Page-Duration-ms'] = int(duration * 1000)
        logger.info('duration:%s url:%s parameters:%s', duration, request.path, request.GET.dict())

        duration = int(duration * 1000)

        if duration > 300:
            capture_message("slow request for url %s with %s" % (request.build_absolute_uri(),duration))

        return response

    def process_exception(self,request,exception):
        # 增加对异常出现的处理:上报sentry和钉钉
        if exception:
            message = "url:{url} ** msg:{error}````{tb}````".format(
                url=request.build_absolute_uri(),
                error = repr(exception),
                tb=traceback.format_exc()
            )

            logger.warning(message)

            dingtalk.send(message)

            capture_exception(exception)

        return HttpResponse('Error processing the request,please contact the system administrator.',status=500)
